package com.jwb.pub.serviceImpl;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jwb.pub.dao.BaseDAO;
import com.jwb.pub.model.JavaModel;
import com.jwb.pub.model.Page;
import com.jwb.pub.service.UserDictService;

@Service
@Slf4j
public class UserDictServiceImpl implements UserDictService {

	@Autowired
	private BaseDAO baseDAO;
	/**
	 * 生成js 数据字典
	 * @param jspath
	 * @return
	 */
	public JSONObject generateUserDictJS(String jspath,String localjs)
	{
		JSONObject result = new JSONObject();
		JSONObject jObject = new JSONObject();		
		JSONObject jObject2 = new JSONObject();	
		
		try
      	{    
			
			String sql="select distinct dict_name from USER_DICT t  where sts='A'";			
			jObject=baseDAO.findBySqlToJosn(sql);			
			JSONArray jarray = jObject.getJSONArray("list");
			if(jarray.size()>0)
			{
				FileOutputStream fos = new FileOutputStream(jspath);
				BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
						fos, "UTF-8"));
				
				   for(int i=0;i<jarray.size();i++){
						JSONObject jso = jarray.getJSONObject(i);
						String dictName = jso.getString("dict_name");
						String sqlStr="";
					
							sqlStr="select dict_name, code, code_desc, display_order,remarks"+
									  " from user_dict"+
									  " where sts = 'A'"+
									  "  and dict_name = '"+dictName+"'"+
									  " order by display_order";
					
						
						jObject2=baseDAO.findBySqlToJosn(sqlStr);	
						JSONArray jarray2 = jObject2.getJSONArray("list");
						String str = "var " + dictName + "="
								+  "[];/r/n";
						if(jarray2.size()>0)
						{
							 str = "var " + dictName + "="
									+  ""+jarray2.toString()+";\r\n";
						}
						
						bw.write(str);							
						log.info(str);
					}
				   bw.close();
				   FileUtils.copyFile(new File(jspath),new File(localjs));
				   result.put("respCode", "0");
				   result.put("respDesc", "success");   
			}
			else
			{
				result.put("respCode", "9");
				result.put("respDesc", "无字典数据");
			}
			
			return result;
      	}   
      	catch(Exception e)
      	{
      		result.put("respCode", "9");
			result.put("respDesc", "系统繁忙");
			e.printStackTrace();
      	}
		
		
		
		
		return result;
	}
	@Override
	public JSONObject userDictDetailList(JSONObject jsdata) {
    JSONObject jsobject = new JSONObject();	
		try
      	{   
      		
			
			
			 String dict_id=!jsdata.containsKey("dict_id") ? "" : jsdata.getString("dict_id");	 	
			 String sqlWhere="";
      		 String sqlOrder="";
			 String sql="SELECT CODE,code_desc,display_order,remarks,dict_logo FROM user_dict t WHERE 1=1 AND t.sts='A' " ; 
			    if (null != dict_id && !"".equals(dict_id))
				{
					sqlWhere += " and dict_id = "+dict_id;
				}   
			   
			    sqlOrder=" ORDER BY t.display_order ";
			    sql+=sqlWhere+sqlOrder;	       
			    jsobject=baseDAO.findBySqlToJosn(sql, "mastlist");
			    
			    JSONArray jsarry = jsobject.getJSONArray("mastlist");		    
			  
		    	for(int i=0;i<jsarry.size();i++){
		    		 JSONObject jso2 = jsarry.getJSONObject(i);
		    		 String sqlWhere2="";
		      		 String sqlOrder2="";
					 String sql2="SELECT  CODE,code_desc,display_order,remarks,dict_logo FROM user_dict t WHERE 1=1 AND t.sts='A' ";
					 if (null != dict_id)
						{
							sqlWhere2 += " and dict_parent_id = "+dict_id;
							
						}   
					   
					 sqlOrder2=" ORDER BY t.display_order ";
					 sql2+=sqlWhere2+sqlOrder2;	
					 JSONObject jsobject2 =baseDAO.findBySqlToJosn(sql2, "detaillist");
					 JSONArray jarray = jsobject2.getJSONArray("detaillist");
					 jso2.put("detaillist", jarray);
					
		    	}
		
      	}   
      	catch(Exception e)
      	{
      		
      	}
      	
		return jsobject;
	}
	@Override
	public JSONObject userDictDetailSave(JSONObject jsdata) {
		   JSONObject jsobject = new JSONObject();	
		   jsobject.put("respCode", "-1");
		   jsobject.put("respDesc", "数据获取异常");
		   String sql="";
		   String dict_id=!jsdata.containsKey("dict_id") ? "" : jsdata.getString("dict_id");	
		   String code=!jsdata.containsKey("code") ? "" : jsdata.getString("code");
		   String code_desc=!jsdata.containsKey("code_desc") ? "" : jsdata.getString("code_desc");
		   String dict_logo=!jsdata.containsKey("dict_logo") ? "" : jsdata.getString("dict_logo");
		   String display_order=!jsdata.containsKey("display_order") ? "0" : jsdata.getString("display_order");
		   String remarks=!jsdata.containsKey("remarks") ? "" : jsdata.getString("remarks");		   
		   JSONArray jsonarr=!jsdata.containsKey("detaillist") ? new JSONArray() : jsdata.getJSONArray("detaillist");
		   int  cnt=0;
		  
			try
	      	{   			
						 
				 if("".equals(dict_id))
				 {
					//增加
					 sql="select count(*) cnt from user_dict where code='"+code+"' and sts='A'";
					 cnt=baseDAO.findBySqlCnt(sql);
				 }
				 else
				 {
					 //修改
					 sql="select count(*) cnt from user_dict where code='"+code+"' and sts='A' and  dict_id<>"+dict_id;
					 cnt=baseDAO.findBySqlCnt(sql);
				 }
				 if(cnt>0)
				 {
					   jsobject.put("respCode", "-1");
					   jsobject.put("respDesc", "字典编码重复!");
					   return jsobject;
				 }
				 
				 
				 LinkedHashMap<String,ArrayList<JavaModel>> map = new LinkedHashMap<String,ArrayList<JavaModel>>();
				 ArrayList<JavaModel> list = new ArrayList<JavaModel>();
				 if("".equals(dict_id))
				 {
					
					 int newid=baseDAO.getSeqId("services", "user_dict");	
					 dict_id=String.valueOf(newid);
					//增加
					sql="insert into user_dict "+
						 " (dict_name,"+
						 "  code,"+
						 "  code_desc,"+
						 "  display_order,"+
						 "  remarks,"+						
						 "  sts,"+						
						 "  dict_parent_id,"+
						"   dict_logo,"+
						"   dict_id,"+
						"   dict_type)"+
						" values"+
						"  (?,"+
						"   ?,"+
						"   ?,"+
						"   ?,"+
						"   ?,"+						
						"   ?,"+					
						"   ?,"+
						"   ?,"+
						"   ?,"+
						"   ?)";	
					String dict_name="dict_name";
					String sts="A";
					String dict_parent_id="-1";
					String dict_type="1";
		  			list = new ArrayList<JavaModel>();
		  			list.add(new JavaModel(dict_name));
		  			list.add(new JavaModel(code));
		  			list.add(new JavaModel(code_desc));
		  			list.add(new JavaModel(display_order));
		  			list.add(new JavaModel(remarks));
		  			list.add(new JavaModel(sts));
		  			list.add(new JavaModel(dict_parent_id));
		  			list.add(new JavaModel(dict_logo));
		  			list.add(new JavaModel(newid));
		  			list.add(new JavaModel(dict_type));
		  			map.put(sql, list);
					 
				 }
				 else
				 {
					 //修改
					 sql=" update user_dict "+
						 "  set dict_name = ?, "+
					     "  code = ?, "+
					     "  code_desc = ?, "+
					     "  display_order = ?, "+
					     "  remarks = ?, "+					   
					     "  sts = ?, "+					   
					     "  dict_parent_id = ?,"+
					     "  dict_logo = ?, "+
					     "  dict_type = ?"+
					" where dict_id = ? and sts='A' ";
					 String dict_name="dict_name";
						String sts="A";
						String dict_parent_id="-1";
						String dict_type="1";
					 list = new ArrayList<JavaModel>();
			  			list.add(new JavaModel(dict_name));
			  			list.add(new JavaModel(code));
			  			list.add(new JavaModel(code_desc));
			  			list.add(new JavaModel(display_order));
			  			list.add(new JavaModel(remarks));
			  			list.add(new JavaModel(sts));
			  			list.add(new JavaModel(dict_parent_id));
			  			list.add(new JavaModel(dict_logo));
			  			list.add(new JavaModel(dict_type));
			  			list.add(new JavaModel(dict_id));
			  			map.put(sql, list);
				 }
				 
				 sql="delete from user_dict where dict_parent_id=? and sts='A'";
		  		 list = new ArrayList<JavaModel>();
		  		 list.add(new JavaModel(dict_id));
		  		 map.put(sql, list);
		  		 
		  		 
		  		sql="insert into user_dict "+
						 " (dict_name,"+
						 "  code,"+
						 "  code_desc,"+
						 "  display_order,"+
						 "  remarks,"+						
						 "  sts,"+						
						 "  dict_parent_id,"+
						"   dict_logo,"+
//						"   dict_id,"+
						"   dict_type)"+
						" values ";
		
		  		 for(int i=0;i<jsonarr.size();i++)
		  		 {
		  			sql +=" (?,"+
						"   ?,"+
						"   ?,"+
						"   ?,"+
						"   ?,"+						
						"   ?,"+					
						"   ?,"+
						"   ?,"+
//						"   ?,"+
						"   ?)";
	  				if(i!=jsonarr.size()-1){
	  					sql +=",";
	  				}
		  		 }
		  		list = new ArrayList<JavaModel>();
		  		 for(int i=0;i<jsonarr.size();i++)
		  		 {
		  			
		  			    JSONObject jso=jsonarr.getJSONObject(i);
						String dict_name_a=code;
						String sts_a="A";					
						String dict_type_a="1";
						String dict_parent_id_a=dict_id;
						String code_a=!jso.containsKey("code") ? "" : jso.getString("code");
						String code_desc_a=	!jso.containsKey("code_desc") ? "" : jso.getString("code_desc");
						String remarks_a=!jso.containsKey("remarks") ? "" : jso.getString("remarks");
						String dict_logo_a=!jso.containsKey("dict_logo") ? "" : jso.getString("dict_logo");	
						String display_order_a=!jso.containsKey("display_order") ? "0" : jso.getString("display_order");			  			
			  			list.add(new JavaModel(dict_name_a));
			  			list.add(new JavaModel(code_a));
			  			list.add(new JavaModel(code_desc_a));
			  			list.add(new JavaModel(display_order_a));
			  			list.add(new JavaModel(remarks_a));
			  			list.add(new JavaModel(sts_a));
			  			list.add(new JavaModel(dict_parent_id_a));
			  			list.add(new JavaModel(dict_logo_a));
			  			//list.add(new JavaModel(newid));
			  			list.add(new JavaModel(dict_type_a));
			  		
		  		 }
		  		 
		  		if(list.size()>0){
		  			map.put(sql, list);
		  		}
		  		
		  		
		  		 boolean flag = baseDAO.excuteBatchOrderedSql(map);
		  		if(!flag){
	  				jsobject.put("respCode", "-1");
	  	           	jsobject.put("respDesc", "保存失败");  
	  	           	return jsobject;
	  			} 
				 jsobject.put("respCode", "0");
				 jsobject.put("respDesc", "保存成功");
	      	}   
	      	catch(Exception e)
	      	{
	      		
	      	}
	      	
			return jsobject;
	}
	
	
	
	public JSONObject udDetailList(JSONObject jsdata, Page page) {
	    JSONObject jsobject = new JSONObject();	
			try
	      	{   
	      		
				
				
				 String keyword=!jsdata.containsKey("keyword") ? "" : jsdata.getString("keyword");	 	
				 String sqlWhere="";
	      		 String sqlOrder="";
				 String sql="SELECT dict_id, CODE, code_desc, display_order, remarks, dict_logo,dict_type "+
							"  FROM user_dict t "+
							" WHERE (dict_name = 'dict_name' AND t.sts = 'A' AND (code_desc LIKE '%"+keyword+"%' or remarks LIKE '%"+keyword+"%'    ) ) "+
							"    OR (CODE IN (SELECT DISTINCT dict_name "+
							"                   FROM user_dict "+
							"                  WHERE dict_name <> 'dict_name' "+
							"                    AND (code_desc LIKE '%"+keyword+"%' or remarks LIKE '%"+keyword+"%'    ) "+
							"                    AND sts = 'A')) ";				   
				    sqlOrder=" ORDER BY t.dict_id desc,t.display_order ";
				    sql+=sqlWhere+sqlOrder;	       
				    jsobject=baseDAO.findBySqlToJosn(sql,page, "mastlist");
				 
				    JSONArray jsarry = jsobject.getJSONArray("mastlist");		    
				  
			    	for(int i=0;i<jsarry.size();i++){
			    		 JSONObject jso2 = jsarry.getJSONObject(i);
			    		 String sqlWhere2="";
			      		 String sqlOrder2="";
						 String sql2="SELECT  dict_id,CODE,code_desc,display_order,remarks,dict_logo,dict_type FROM user_dict t WHERE 1=1 AND t.sts='A' ";
						 if (null != jsarry.getJSONObject(i).getString("dict_id") && !"".equals(jsarry.getJSONObject(i).getString("dict_id") ))
						 {
								sqlWhere2 += " and dict_parent_id = "+jsarry.getJSONObject(i).getString("dict_id");
								
						 }   
						   
						 sqlOrder2=" ORDER BY t.display_order ";
						 sql2+=sqlWhere2+sqlOrder2;	
						 JSONObject jsobject2 =baseDAO.findBySqlToJosn(sql2, "detaillist");
						 JSONArray jarray = jsobject2.getJSONArray("detaillist");
						 jso2.put("detaillist", jarray);
						
			    	}
			
	      	}   
	      	catch(Exception e)
	      	{
	      		
	      	}
	      	
			return jsobject;
		}
	@Override
	public JSONObject udDel(JSONObject jsdata) {
		// TODO Auto-generated method stub
		   JSONObject jsobject = new JSONObject();	
		   jsobject.put("respCode", "-1");
		   jsobject.put("respDesc", "数据获取异常");
		   LinkedHashMap<String,ArrayList<JavaModel>> map = new LinkedHashMap<String,ArrayList<JavaModel>>();
		   ArrayList<JavaModel> list = new ArrayList<JavaModel>();
		   String dict_id=!jsdata.containsKey("dict_id") ? "" : jsdata.getString("dict_id");
		   String sql="update user_dict set  sts='P'  where dict_id=? ";
		   list = new ArrayList<JavaModel>();
 		   list.add(new JavaModel(dict_id)); 			
 		   map.put(sql, list);
 		   sql="update user_dict set  sts='P'  where dict_parent_id =? ";
		   list = new ArrayList<JavaModel>();
		   list.add(new JavaModel(dict_id)); 			
		   map.put(sql, list); 
		   boolean flag = baseDAO.excuteBatchOrderedSql(map);
	  		if(!flag){
 				jsobject.put("respCode", "-1");
 	           	jsobject.put("respDesc", "删除失败");  
 	           	return jsobject;
 			} 
			 jsobject.put("respCode", "0");
			 jsobject.put("respDesc", "删除成功");
		   return jsobject;
	}
}


